<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

/**
 * @property integer $id
 * @property string $name
 * @property string $email
 * @property string $phone
 * @property string $password
 * @property string $avatar
 * @property integer $status
 * @property Carbon $created_at
 * @property Carbon $updated_at
 * @property integer $is_super
 * @property Collection $roles
 * @property Collection $permissions
 */
class Admin extends Authenticatable
{
    protected $guarded = [];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'is_super' => 'boolean',
        'last_login_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'admin_has_roles', 'admin_id', 'role_id');
    }

    /**
     * 获取管理员的所有权限
     */
    public function permissions()
    {
        return $this->roles()->with('permissions')->get()
            ->pluck('permissions')
            ->flatten()
            ->unique('id');
    }

    /**
     * 检查管理员是否有某个权限
     */
    public function hasPermission($permissionSlug)
    {
        return $this->permissions()->contains('slug', $permissionSlug);
    }

    /**
     * 获取管理员的菜单树
     */
    public function getMenuTree(): array
    {
        $permissions = $this->permissions()->sortBy('sort');
        return $this->buildMenuTree($permissions);
    }

    /**
     * 递归构建菜单树
     */
    private function buildMenuTree($permissions, $parentId = 0): array
    {
        $tree = [];

        foreach ($permissions as $permission) {
            if ($permission->parent_id == $parentId) {
                $children = $this->buildMenuTree($permissions, $permission->id);

                $menu = [
                    'id' => $permission->id,
                    'title' => $permission->name,
                    'icon' => $permission->icon,
                    'route' => $permission->route,
                    'component' => $permission->component,
                    'children' => $children
                ];

                $tree[] = $menu;
            }
        }

        return $tree;
    }

    public function getRoleIds(): array
    {
        return $this->roles()->pluck('id')->toArray() ?? [];
    }

    public function getRoleNames(): array
    {
        return $this->roles()->pluck('name')->toArray() ?? [];
    }

    public function syncRoles(array $roleIds): void
    {
        $this->roles()->sync($roleIds);
    }

    public function removeRoles(): void
    {
        $this->roles()->detach();
    }
}
